﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using aier.xrm.wcf;
using Microsoft.Xrm.Sdk;

namespace aier.business.logic
{
    public class LeadBll
    {
        public LeadDal leadDal { get; set; }

        public ScreenCustomerDal screenCustomerDal { get; set; }
        public ScreenResultDal screenResultDal { get; set; }

        public ReferralPatientDal referralPatientDal { get; set; }
        public ILog log { get; set; }
        public CommonWcf commonWcf { get; set; }
        public ResResult resResult { get; set; }

        public ChineseToLetterBll toLetterBll { get; set; }


        public IEnumerable<dynamic> QueryPatientLeadPageByModifiedOn(DateTime modifiedOn, int pageNum, int pageSize)
        {
            int skipNum = (pageNum - 1) * pageSize;
            return leadDal.QueryPatientLeadPageByModifiedOn(modifiedOn,skipNum,pageSize);
        }


        public IEnumerable<dynamic> QueryReferralShipPageByModifiedOn(DateTime modifiedOn, int pageNum, int pageSize)
        {
            int skipNum = (pageNum - 1) * pageSize;
            return referralPatientDal.QueryReferralShipPageByModifiedOn(modifiedOn, skipNum, pageSize);
        }



        public LeadView QueryStudentInfoById(string leadid)
        {
            var studentInfo = leadDal.QueryStudentInfoById(leadid);
            return studentInfo;
        }

        /// <summary>
        /// 对学生按名字首字符分组
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="classId"></param>
        /// <returns></returns>
        public List<GroupResult<LeadView>> QueryLeadInfoBySchoolIdAndClassNum(string schoolId, string classId)
        {
            var leadList =  leadDal.QueryLeadInfoBySchoolIdAndClassNum(schoolId, classId)?.ToList();
            return  this.GroupData(leadList);
        }

        /// <summary>
        /// 对数据根据首字母分组
        /// </summary>
        /// <param name="recommendViews"></param>
        /// <returns></returns>
        private List<GroupResult<LeadView>> GroupData(List<LeadView> doctorList)
        {
            var dicResult = doctorList.Where(t => !string.IsNullOrWhiteSpace(t.FullName)).GroupBy(t => toLetterBll.startWithFirst(t.FullName[0])).ToDictionary(t => t.Key, t => t.ToList());
            var doctorListnull = doctorList.Where(t => string.IsNullOrWhiteSpace(t.FullName));
            if (doctorListnull.ToList().Count > 0)
            {
                Dictionary<string, List<LeadView>> dicResultnull = new Dictionary<string, List<LeadView>>();
                dicResultnull.Add("#", doctorListnull.ToList());
                dicResult = dicResult.OrderBy(t => t.Key).Concat(dicResultnull).ToDictionary(k => k.Key, v => v.Value);
            }
            else {
                dicResult = dicResult.OrderBy(t => t.Key).ToDictionary(k => k.Key, v => v.Value);
            }
            List<GroupResult<LeadView>> groupResults = new List<GroupResult<LeadView>>();

            dicResult.ToList().ForEach(item =>
            {
                GroupResult<LeadView> groupResult = new GroupResult<LeadView>();
                groupResult.groupname = item.Key;
                groupResult.grouplist = item.Value;
                groupResults.Add(groupResult);
            });
            return groupResults;
        }

        /// <summary>
        /// 解除关系
        /// </summary>
        /// <param name="leadInfo"></param>
        public void Disassociate(LeadInfo leadInfo)
        {
            //EntityReference pef = new EntityReference("lead", leadInfo.leadid);
            //List<EntityReference> erList = new List<EntityReference>();
            //if (leadInfo.tag != null && leadInfo.tag.Count() != 0)
            //{
            //    for (int i = 0; i < leadInfo.tag.Count(); i++)
            //    {
            //        erList.Add(new EntityReference("new_tag", leadInfo.tag[i]));
            //    }
            //    commonWcf.ExceDisassociate(pef, erList, "new_lead_new_tag");
            //}

        }

        public Guid[] BatchCreateLead(LeadDto[] leadDtos, Guid ownerid)
        {
			List<Entity> leadXrms = new List<Entity>(leadDtos.Count());

			foreach (LeadDto leadDto in leadDtos)
            {
				LeadXrm leadXrm = new LeadXrm();
			
                if (leadDto.new_inputingtime.HasValue)
                    leadXrm.new_inputingtime = leadDto.new_inputingtime.Value;
                leadXrm.address1_telephone1 = leadDto.address1_telephone1;
                leadXrm.description = leadDto.description;
				leadXrm.lastname = leadDto.lastname;
                if(leadDto.new_age.HasValue)
					leadXrm.new_age = leadDto.new_age.Value;
				if (leadDto.new_birthdate.HasValue)
                    leadXrm.new_birthdate = leadDto.new_birthdate.Value;
                leadXrm.new_citizenid = leadDto.new_citizenid;
				if (leadDto.new_datasource.HasValue)
					leadXrm.new_datasource = leadDto.new_datasource.Value;
				if (leadDto.new_disease.HasValue)
					leadXrm.new_disease = leadDto.new_disease.Value;
				if (leadDto.new_gender.HasValue)
					leadXrm.new_gender = leadDto.new_gender.Value;
				if (leadDto.new_mxqd.HasValue)
					leadXrm.new_mxqd = leadDto.new_mxqd.Value;
				if (leadDto.new_patientsource.HasValue)
					leadXrm.new_patientsource = leadDto.new_patientsource.Value;
				leadXrm.new_sourceremark = leadDto.new_reservationdate;
				var leadEntity = leadXrm.AsCrmEntity();
				leadXrms.Add(leadEntity);
			}
            return  commonWcf.ExecultParallelMutipleCreate(leadXrms, ownerid);
		}

        public Guid CreatePatient(ReferralPatientDto referralPatientDto,Guid ownerid)
        {
            Patient patient = new Patient();
            patient.fullname = referralPatientDto.name;
            patient.new_gender = referralPatientDto.sex;
            patient.new_age = referralPatientDto.age;
            patient.new_birthdate = referralPatientDto.birthdate;
            patient.address1_telephone1 = referralPatientDto.telephone;
            patient.new_citizenid = referralPatientDto.citizenid;
            patient.address1_name = referralPatientDto.address;
            patient.description = referralPatientDto.description;
            patient.new_patientsource = referralPatientDto.patientsource;
            patient.new_sourceremark = referralPatientDto.sourceremark;
            if (referralPatientDto.promotionsource != 0)
                patient.new_mxqd = referralPatientDto.promotionsource;
            patient.new_disease = referralPatientDto.disease;
            patient.initialcommunication = referralPatientDto.infantscreening;
            patient.new_popularscience = referralPatientDto.popularscience;
            patient.new_inputingtime = referralPatientDto.createtime;
            var leadEntity = patient.AsCrmEntity();
            return commonWcf.CreateEntityProxy(ownerid, leadEntity);
        }

        public Int64 CreateReferralPatient(ReferralPatientDto referralPatientDto, SystemUser systemUser, Guid leadid)
        {
            ReferralShip referralShip = new ReferralShip();
            referralShip.leadid = leadid;
            referralShip.referral_outoa = referralPatientDto.referraloutoa;
            referralShip.referral_outname = referralPatientDto.referraloutname;
            referralShip.referral_outemedicalhospitalid = referralPatientDto.referraloutcode;
            referralShip.referral_outhospitalname = referralPatientDto.referralouthospital;


            referralShip.referral_incrm = systemUser.domainName;
            referralShip.referral_inoa = systemUser.employeeId;
            referralShip.referral_inname = systemUser.fullName;
            referralShip.referral_inemedicalhospitalid = systemUser.new_emedicalhospitalid;
            referralShip.referral_inhospitalname = systemUser.hospitalName;

            DateTime nowDate = DateTime.Now;
            referralShip.createdon = Convert.ToDateTime(nowDate.ToString("yyyy-MM-dd HH:mm:ss"));
            referralShip.modifiedon = Convert.ToDateTime(nowDate.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!string.IsNullOrWhiteSpace(referralPatientDto.description))
                referralShip.description = referralPatientDto.description;
            referralShip.new_patientsource = referralPatientDto.patientsource;
            referralShip.new_disease = referralPatientDto.disease;


            referralShip.isfollow = referralPatientDto.isfollow;
            if (referralPatientDto.isfollow == 1)
                referralShip.followdate = referralPatientDto.followdate;
            else
                referralShip.followdate = null;
            referralShip.identifydoctor = referralPatientDto.identifydoctor;
            referralShip.expectedoperation = referralPatientDto.expectedoperation;
            referralShip.safetydemands = referralPatientDto.safetydemands;
            referralShip.pricesensitivity = referralPatientDto.pricesensitivity;
            referralShip.benefitsavailable = referralPatientDto.benefitsavailable;
            return referralPatientDal.SaveReferralPatient(referralShip);
        }

        /// <summary>
        /// 添加客户信息
        /// </summary>
        /// <param name="leadInfo"></param>
        /// <returns></returns>
        public ResResult SaveLeadInfo(LeadInfo leadInfo)
        {
            try
            {
                Entity entity = leadInfo.AsCrmEntity();
                Guid lguid = Guid.Empty;
                //添加客户信息
                if (Guid.Empty.Equals(leadInfo.userid))
                {
                    lguid = commonWcf.CreateEntity(entity);
                }
                else
                {
                    if (leadInfo.userid != leadInfo.ownerid) {
                        lguid = commonWcf.CreateEntity(entity);
                    }
                    else
                        lguid = commonWcf.CreateEntityProxy(leadInfo.userid, entity);
                }
                //创建关系
                //try
                //{

                //    EntityReference pef = new EntityReference("lead", lguid);
                //    List<EntityReference> erList = new List<EntityReference>();
                //    if (leadInfo.tag != null && leadInfo.tag.Count() != 0)
                //    {
                //        for (int i = 0; i < leadInfo.tag.Count(); i++)
                //        {
                //            erList.Add(new EntityReference("new_tag", leadInfo.tag[i]));
                //        }
                //        commonWcf.ExceAisassociateMToMEntities(pef, erList, "new_lead_new_tag");
                //    }

                //}
                //catch (Exception ex)
                //{
                //    log.Error("SaveLeadInfo方法 :创建关系出错," + ex.Message);
                //}
                return resResult.SuccessResult(lguid);

            }
            catch (Exception ex)
            {
                log.Error("SaveLeadInfo方法 :创建客户信息," + ex.Message);
                throw ex;
                //return resResult.FailResult("LeadBll->SaveLeadInfo Error:" + ex.Message);
            }
        }

        /// <summary>
        /// 更新潜在客户信息
        /// </summary>
        /// <param name="leadInfo"></param>
        /// <returns></returns>
        public ResResult UpdateLeadBase(LeadInfo leadInfo)
        {
            ResResult resResult = new ResResult();
            try
            {
                if (leadInfo == null)
                {
                    log.Error("UpdateLeadBase 方法：传入对象为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:传入对象为空 ");
                }
                if (Guid.Empty.Equals(leadInfo.leadid))
                {
                    log.Error("UpdateLeadBase 方法：对象id为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:对象id为空 ");
                }
                if (string.IsNullOrWhiteSpace(leadInfo.lastname))
                {
                    log.Error("UpdateLeadBase 方法：客户姓名为空");
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:客户姓名为空 ");
                }

                if (QueryLeadInfoById(leadInfo.leadid) == null)
                {
                    return resResult.FailResult("LeadBll->UpdateLeadBase Error:该潜在用户不存在 ");
                }
                //添加客户信息
                Entity entity = leadInfo.AsCrmEntity();
                //添加客户信息
                if (Guid.Empty.Equals(leadInfo.userid))
                {
                    commonWcf.UpdateEntityById(entity);
                }
                else
                {
                    commonWcf.UpdateEntityProxyById(leadInfo.userid, entity);
                }
                return resResult.SuccessResult(leadInfo.leadid);
            }
            catch (Exception ex)
            {
                log.Error("UpdateLeadBase方法 :" + ex.Message);
                throw ex;
                //return resResult.FailResult("LeadBll->UpdateLeadBase Error: " + ex.Message);
            }

        }


        /// <summary>
        /// 根据姓名、手机、身份证查询潜在客户
        /// </summary>
        /// <param name="condition">姓名、手机、身份证条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns></returns>
        public PageResult<LeadView> QueryLeadInfoList(string condition, int pageNum, int pageSize)
        {
            PageResult<LeadView> pageResult = new PageResult<LeadView>();
            try
            {
                string idCard = string.Empty;
                string newLeadname = string.Empty;
                string newMobile = string.Empty;


                if (CommonUtil.IsIDCard(condition))
                {
                    //如果为身份证
                    idCard = condition;
                }
                if (CommonUtil.IsContainChinese(condition))
                {
                    //如果为姓名
                    newLeadname = condition;
                }
                if (CommonUtil.IsMobile(condition))
                {
                    //如果为手机
                    newMobile = condition;
                }

                if (!string.IsNullOrWhiteSpace(idCard) && !string.IsNullOrWhiteSpace(newLeadname) && !string.IsNullOrWhiteSpace(newMobile))
                {
                    idCard = condition;
                    newLeadname = condition;
                    newMobile = condition;
                }

                var leadListView = leadDal.QueryLeadPageByConditions(newLeadname, newMobile, idCard, pageNum, pageSize + 1);
                pageResult.existsnextdata = leadListView.Count() > pageSize;
                pageResult.total = leadDal.QueryLeadCountByConditions(newLeadname, newMobile, idCard);
                pageResult.datas = leadListView.Skip(0).Take(pageSize).ToList();

                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoList: " + ex.Message);
                return null;
            }
        }

        public PageResult<LeadView> QueryLeadInfoList4Stat(string searchKey, int pageNum, int pageSize, Guid ownerid, Guid screenteamid, DateTime startDate, DateTime endDate, int type)
        {
            PageResult<LeadView> pageResult = new PageResult<LeadView>();
            try
            {
                string idCard = string.Empty;
                string newLeadname = string.Empty;
                string newMobile = string.Empty;


                if (CommonUtil.IsIDCard(searchKey))
                {
                    //如果为身份证
                    idCard = searchKey;
                }
                if (CommonUtil.IsContainChinese(searchKey))
                {
                    //如果为姓名
                    newLeadname = searchKey;
                }
                if (CommonUtil.IsMobile(searchKey))
                {
                    //如果为手机
                    newMobile = searchKey;
                }

                if (!string.IsNullOrWhiteSpace(idCard) && !string.IsNullOrWhiteSpace(newLeadname) && !string.IsNullOrWhiteSpace(newMobile))
                {
                    idCard = searchKey;
                    newLeadname = searchKey;
                    newMobile = searchKey;
                }

                var leadListView = leadDal.QueryLeadPageByConditions4stat(newLeadname, newMobile, idCard, pageNum, pageSize + 1, ownerid,  screenteamid,  startDate,  endDate,  type);
                pageResult.existsnextdata = leadListView.Count() > pageSize;
                pageResult.total = leadDal.QueryLeadCountByConditions4stat(newLeadname, newMobile, idCard, ownerid,  screenteamid,  startDate,  endDate,  type);
                pageResult.datas = leadListView.Skip(0).Take(pageSize).ToList();

                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoList: " + ex.Message);
                return null;
            }
        }
        public PageResult<LeadView> QueryLeadInfoList(string condition, int pageNum, int pageSize, Guid ownerid)
        {
            PageResult<LeadView> pageResult = new PageResult<LeadView>();
            try
            {
                string idCard = string.Empty;
                string newLeadname = string.Empty;
                string newMobile = string.Empty;


                if (CommonUtil.IsIDCard(condition))
                {
                    //如果为身份证
                    idCard = condition;
                }
                if (CommonUtil.IsContainChinese(condition))
                {
                    //如果为姓名
                    newLeadname = condition;
                }
                if (CommonUtil.IsMobile(condition))
                {
                    //如果为手机
                    newMobile = condition;
                }

                if (!string.IsNullOrWhiteSpace(idCard) && !string.IsNullOrWhiteSpace(newLeadname) && !string.IsNullOrWhiteSpace(newMobile))
                {
                    idCard = condition;
                    newLeadname = condition;
                    newMobile = condition;
                }

                var leadListView = leadDal.QueryLeadPageByConditions(newLeadname, newMobile, idCard, pageNum, pageSize + 1,ownerid);
                pageResult.existsnextdata = leadListView.Count() > pageSize;
                pageResult.total = leadDal.QueryLeadCountByConditions(newLeadname, newMobile, idCard,ownerid);
                pageResult.datas = leadListView.Skip(0).Take(pageSize).ToList();

                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoList: " + ex.Message);
                return null;
            }
        }


        /// <summary>
        /// 根据姓名、手机、身份证查询潜在客户
        /// 查询条件为：姓名、手机、身份证
        /// 原程序 LeadBaseServiceImpl/select
        /// </summary>
        /// <param name="customerName">姓名</param>
        /// <param name="phone">手机</param>
        /// <param name="sfz">身份证</param>
        /// <returns></returns>
        public LeadView QueryLeadInfoByConditions(string customerName, string phone, string sfz)
        {
            LeadView lead = leadDal.QueryLeadInfoByConditions(customerName, phone, sfz);
            return lead;
        }
        /// <summary>
        /// 根据客户ID查询客户信息
        /// 查询条件为：客户ID
        /// 原程序 LeadBaseServiceImpl/select
        /// </summary>
        /// <param name="leadId"></param>
        /// <returns></returns>
        public LeadView QueryLeadInfoById(Guid leadid)
        {
            LeadView lead = null;
            lead = leadDal.QueryLeadInfoById(leadid);
            return lead;
        }
        /// <summary>
        /// 根据条件查询leadid
        /// 查询条件为：姓名、负责人ID、身份证、手机号码、座机
        /// 原程序 LeadBaseServiceImpl/queryLeadid
        /// </summary>
        /// <param name="customername">姓名</param>
        /// <param name="ownerid">负责人ID</param>
        /// <param name="citizenid">身份证</param>
        /// <param name="iphoneno">手机号码</param>
        /// <param name="telno">座机</param>
        /// <returns></returns>
        public Guid QueryLeadidByConditions(string customername, Guid ownerid, string citizenid, string iphoneno, string telno)
        {

            Guid lead = Guid.Empty;
            if (string.IsNullOrWhiteSpace(customername))
            {
               // log.Error("LeadBll对象中：QueryLeadidByConditions，customername条件为空");
                return Guid.Empty;
            }
            if (string.IsNullOrWhiteSpace(citizenid) && string.IsNullOrWhiteSpace(iphoneno) && string.IsNullOrWhiteSpace(telno))
            {
                //log.Error("LeadBll对象中：QueryLeadidByConditions，citizenid、iphoneno、telno条件都为空");
                return Guid.Empty;
            }
            lead = leadDal.QueryLeadidByConditions(customername, ownerid, citizenid, iphoneno, telno);
            return lead;
        }

        /// <summary>
        /// 根据leadId获取潜客数据
        /// </summary>
        /// <param name="leadId"></param>
        /// <returns></returns>
        public AccountDetailView GetAccountDetailData(Guid leadId)
        {
            if (leadId != Guid.Empty)
            {
                AccountDetailView accountDetail = leadDal.GetAcountDetailsData(leadId);
                return accountDetail;
            }
            return null;
        }

        public IEnumerable<ScreenResultView> GetAccountScreenDetailData(Guid leadId,Guid screenId)
        {
            IEnumerable<ScreenResultView> screenResultData = null;
            if (leadId != Guid.Empty)
            {
                //Guid screenId = screenCustomerDal.GetMaxScreenByLead(leadId);
                //if (screenId != Guid.Empty)
                {
                    screenResultData = screenResultDal.GetScreenResultsByScreenIdAndCustomerId(screenId, leadId);
                    screenResultData = screenResultData.Where(x =>
                    (x.new_itemid == "XM0014" || x.new_itemid == "XM0010"
                     || x.new_itemid == "XM0047" || x.new_itemid == "XM0049"
                     || x.new_itemid == "XM0050" || x.new_itemid == "XM0052") &&
                      (x.new_contentid == "NR0023" || x.new_contentid == "NR0025"
                     || x.new_contentid == "NR0024" || x.new_contentid == "NR0026"
                     || x.new_contentid == "NR0143" || x.new_contentid == "NR0144"
                     || x.new_contentid == "NR0145" || x.new_contentid == "NR0146"
                     || x.new_contentid == "NR0147" || x.new_contentid == "NR0148"
                     || x.new_contentid == "NR0151")
                     );
                    return screenResultData;
                }
            }
            return null;
        }
    }
}
